/*
 * Copyright (c) 2010-2020 Belledonne Communications SARL.
 *
 * This file is part of linphone-android
 * (see https://www.linphone.org).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.newlink.building.activities.main.settings.viewmodels

import androidx.databinding.ViewDataBinding
import androidx.lifecycle.MutableLiveData
import com.newlink.building.R
import com.newlink.building.activities.main.settings.Module_Phone_SettingListenerStub
import com.newlink.building.utils.Module_Phone_AppUtils
import com.newlink.building.utils.Module_Phone_Event
import com.newlink.building.utils.Module_Phone_PermissionHelper
import org.linphone.core.Core
import org.linphone.core.CoreListenerStub
import org.linphone.core.EcCalibratorStatus
import org.linphone.core.Factory
import org.linphone.core.MediaEncryption
import org.linphone.core.tools.Log
import java.io.File
import java.util.Locale

class Module_Phone_CallSettingsViewModel : Module_Phone_GenericSettingsViewModel() {

    //region tmp var
    var echoCancellationTmp: Boolean = false
    var codecBitrateIndexTmp: Int = -1
    var videoSizeIndexTmp: Int = -1
    var videoPresetIndexTmp: Int = 0
    var preferredFpsIndexTmp: Int = -1
    var ringtoneIndexTmp: Int = -1
    var vibrateOnIncomingCallTmp: Boolean = false
    var acceptEarlyMediaTmp: Boolean = false
    var ringDuringEarlyMediaTmp: Boolean = false
    var videoPayloadNumTmp: Int = 96
    var audioPayloadNumTmp: Int = 96

    //endregion

    lateinit var videoCodecListener: Module_Phone_SettingListenerStub

    lateinit var audioCodecListener: Module_Phone_SettingListenerStub

    val askAudioRecordPermissionForEchoCancellerCalibrationEvent: MutableLiveData<Module_Phone_Event<Boolean>> by lazy {
        MutableLiveData<Module_Phone_Event<Boolean>>()
    }

    val askAudioRecordPermissionForEchoTesterEvent: MutableLiveData<Module_Phone_Event<Boolean>> by lazy {
        MutableLiveData<Module_Phone_Event<Boolean>>()
    }

    val echoCancellationListener = object : Module_Phone_SettingListenerStub() {
        override fun onBoolValueChanged(newValue: Boolean) {
            echoCancellation.value = newValue
        }
    }

    private var echoTesterIsRunning = false
    val echoTesterStatus = MutableLiveData<String>()

    val deviceRingtoneListener = object : Module_Phone_SettingListenerStub() {
        override fun onBoolValueChanged(newValue: Boolean) {
            core.ring = if (newValue) null else prefs.defaultRingtonePath
        }
    }
    val deviceRingtone = MutableLiveData<Boolean>()

    val videoPayloadNum = MutableLiveData<Int>()
    val audioPayloadNum = MutableLiveData<Int>()

    val echoCalibration = MutableLiveData<String>()
    val videoCodecs = MutableLiveData<ArrayList<ViewDataBinding>>()

    val echoCancellerCalibrationListener = object : Module_Phone_SettingListenerStub() {
        override fun onClicked() {
            if (Module_Phone_PermissionHelper.get().hasRecordAudioPermission()) {
                startEchoCancellerCalibration()
            } else {
                askAudioRecordPermissionForEchoCancellerCalibrationEvent.value = Module_Phone_Event(true)
            }
        }
    }

    val echoTesterListener = object : Module_Phone_SettingListenerStub() {
        override fun onClicked() {
            if (Module_Phone_PermissionHelper.get().hasRecordAudioPermission()) {
                if (echoTesterIsRunning) {
                    stopEchoTester()
                } else {
                    startEchoTester()
                }
            } else {
                askAudioRecordPermissionForEchoTesterEvent.value = Module_Phone_Event(true)
            }
        }
    }
    val echoCancellation = MutableLiveData<Boolean>()
    val listener = object : CoreListenerStub() {
        override fun onEcCalibrationResult(core: Core, status: EcCalibratorStatus, delayMs: Int) {
            if (status == EcCalibratorStatus.InProgress) return
            echoCancellerCalibrationFinished(status, delayMs)
        }
    }

    fun startEchoCancellerCalibration() {
        if (echoTesterIsRunning) {
            stopEchoTester()
        }

        core.addListener(listener)
        core.startEchoCancellerCalibration()
        echoCalibration.value =
            prefs.getString(R.string.audio_settings_echo_cancellation_calibration_started)
    }

    fun echoCancellerCalibrationFinished(status: EcCalibratorStatus, delay: Int) {
        core.removeListener(listener)

        when (status) {
            EcCalibratorStatus.InProgress -> {
                echoCalibration.value =
                    prefs.getString(R.string.audio_settings_echo_cancellation_calibration_started)
            }

            EcCalibratorStatus.DoneNoEcho -> {
                echoCalibration.value =
                    prefs.getString(R.string.audio_settings_echo_cancellation_calibration_no_echo)
            }

            EcCalibratorStatus.Done -> {
                echoCalibration.value =
                    prefs.getString(R.string.audio_settings_echo_cancellation_calibration_value)
                        .format(delay)
            }

            EcCalibratorStatus.Failed -> {
                echoCalibration.value =
                    prefs.getString(R.string.audio_settings_echo_cancellation_calibration_failed)
            }
        }
        echoCancellation.value = status != EcCalibratorStatus.DoneNoEcho
    }

    fun startEchoTester() {
        echoTesterIsRunning = true
        echoTesterStatus.value =
            prefs.getString(R.string.audio_settings_echo_tester_summary_is_running)
        core.startEchoTester(0)
    }

    fun stopEchoTester() {
        echoTesterIsRunning = false
        echoTesterStatus.value =
            prefs.getString(R.string.audio_settings_echo_tester_summary_is_stopped)
        core.stopEchoTester()
    }

    val echoShowFrameRate = MutableLiveData<Boolean>()

    val codecBitrateIndex = MutableLiveData<Int>()
    val codecBitrateLabels = MutableLiveData<ArrayList<String>>()
    private val codecBitrateValues = arrayListOf(10, 15, 20, 36, 64, 128)

    val codecBitrateListener = object : Module_Phone_SettingListenerStub() {
        override fun onListValueChanged(position: Int) {
            codecBitrateIndex.value = position
        }
    }

    val ringtoneListener = object : Module_Phone_SettingListenerStub() {
        override fun onListValueChanged(position: Int) {
            ringtoneIndex.value = position
        }
    }
    val ringtoneIndex = MutableLiveData<Int>()
    val ringtoneLabels = MutableLiveData<ArrayList<String>>()
    private val ringtoneValues = arrayListOf<String>()
    val showRingtonesList = MutableLiveData<Boolean>()

    val vibrateOnIncomingCallListener = object : Module_Phone_SettingListenerStub() {
        override fun onBoolValueChanged(newValue: Boolean) {
            vibrateOnIncomingCall.value = newValue
        }
    }
    val vibrateOnIncomingCall = MutableLiveData<Boolean>()

    //    val encryptionListener = object : SettingListenerStub() {
//        override fun onListValueChanged(position: Int) {
//            core.mediaEncryption = MediaEncryption.fromInt(encryptionValues[position])
//            encryptionIndex.value = position
//            if (position == 0) {
//                encryptionMandatory.value = false
//            }
//        }
//    }
    val encryptionIndex = MutableLiveData<Int>()
    val encryptionLabels = MutableLiveData<ArrayList<String>>()
    private val encryptionValues = arrayListOf<Int>()

    //    val encryptionMandatoryListener = object : SettingListenerStub() {
//        override fun onBoolValueChanged(newValue: Boolean) {
//            core.isMediaEncryptionMandatory = newValue
//        }
//    }
    val encryptionMandatory = MutableLiveData<Boolean>()

//    val useTelecomManagerListener = object : SettingListenerStub() {
//        override fun onBoolValueChanged(newValue: Boolean) {
//            if (newValue) {
//                enableTelecomManagerEvent.value = Event(true)
//            } else {
//                if (TelecomHelper.exists()) {
//                    Log.i("[Call Settings] Removing Telecom Manager account & destroying singleton")
//                    TelecomHelper.get().removeAccount()
//                    TelecomHelper.get().destroy()
//                    TelecomHelper.destroy()
//
//                    Log.w("[Call Settings] Disabling Telecom Manager auto-enable")
//                    prefs.manuallyDisabledTelecomManager = true
//                }
//                prefs.useTelecomManager = newValue
//            }
//        }
//    }
//    val useTelecomManager = MutableLiveData<Boolean>()
//    val enableTelecomManagerEvent: MutableLiveData<Event<Boolean>> by lazy {
//        MutableLiveData<Event<Boolean>>()
//    }
//    val api26OrHigher = MutableLiveData<Boolean>()
//
//    val fullScreenListener = object : SettingListenerStub() {
//        override fun onBoolValueChanged(newValue: Boolean) {
//            prefs.fullScreenCallUI = newValue
//        }
//    }
//    val fullScreen = MutableLiveData<Boolean>()
//
//    val overlayListener = object : SettingListenerStub() {
//        override fun onBoolValueChanged(newValue: Boolean) {
//            prefs.showCallOverlay = newValue
//        }
//    }
//    val overlay = MutableLiveData<Boolean>()
//
//    val systemWideOverlayListener = object : SettingListenerStub() {
//        override fun onBoolValueChanged(newValue: Boolean) {
//            if (Version.sdkAboveOrEqual(Version.API23_MARSHMALLOW_60)) {
//                if (newValue) systemWideOverlayEnabledEvent.value = Event(true)
//            }
//            prefs.systemWideCallOverlay = newValue
//        }
//    }
//    val systemWideOverlay = MutableLiveData<Boolean>()
//    val systemWideOverlayEnabledEvent = MutableLiveData<Event<Boolean>>()
//
//    val sipInfoDtmfListener = object : SettingListenerStub() {
//        override fun onBoolValueChanged(newValue: Boolean) {
//            core.useInfoForDtmf = newValue
//        }
//    }
//    val sipInfoDtmf = MutableLiveData<Boolean>()
//
//    val rfc2833DtmfListener = object : SettingListenerStub() {
//        override fun onBoolValueChanged(newValue: Boolean) {
//            core.useRfc2833ForDtmf = newValue
//        }
//    }
//    val rfc2833Dtmf = MutableLiveData<Boolean>()
//
//    val autoStartCallRecordingListener = object : SettingListenerStub() {
//        override fun onBoolValueChanged(newValue: Boolean) {
//            prefs.automaticallyStartCallRecording = newValue
//        }
//    }
//    val autoStartCallRecording = MutableLiveData<Boolean>()
//
//    val autoStartListener = object : SettingListenerStub() {
//        override fun onBoolValueChanged(newValue: Boolean) {
//            prefs.callRightAway = newValue
//        }
//    }
//    val autoStart = MutableLiveData<Boolean>()
//
//    val autoAnswerListener = object : SettingListenerStub() {
//        override fun onBoolValueChanged(newValue: Boolean) {
//            core.isKeepAliveEnabled = newValue
//        }
//    }
//    val autoAnswer = MutableLiveData<Boolean>()
//
//    val autoAnswerDelayListener = object : SettingListenerStub() {
//        override fun onTextValueChanged(newValue: String) {
//            try {
//                core.keepaliveInterval = newValue.toInt()
//            } catch (nfe: NumberFormatException) {
//            }
//        }
//    }
//    val autoAnswerDelay = MutableLiveData<Int>()
//
//    val incomingTimeoutListener = object : SettingListenerStub() {
//        override fun onTextValueChanged(newValue: String) {
//            try {
//                core.incTimeout = newValue.toInt()
//            } catch (nfe: NumberFormatException) {
//            }
//        }
//    }
//    val incomingTimeout = MutableLiveData<Int>()
//
//    val voiceMailUriListener = object : SettingListenerStub() {
//        override fun onTextValueChanged(newValue: String) {
//            voiceMailUri.value = newValue
//            prefs.voiceMailUri = newValue
//        }
//    }
//    val voiceMailUri = MutableLiveData<String>()
//
//    val redirectToVoiceMailIncomingDeclinedCallsListener = object : SettingListenerStub() {
//        override fun onBoolValueChanged(newValue: Boolean) {
//            prefs.redirectDeclinedCallToVoiceMail = newValue
//        }
//    }
//    val redirectToVoiceMailIncomingDeclinedCalls = MutableLiveData<Boolean>()

    val acceptEarlyMediaListener = object : Module_Phone_SettingListenerStub() {
        override fun onBoolValueChanged(newValue: Boolean) {
            acceptEarlyMedia.value = newValue
        }
    }
    val acceptEarlyMedia = MutableLiveData<Boolean>()

    val ringDuringEarlyMediaListener = object : Module_Phone_SettingListenerStub() {
        override fun onBoolValueChanged(newValue: Boolean) {
            ringDuringEarlyMedia.value = newValue
        }
    }
    val ringDuringEarlyMedia = MutableLiveData<Boolean>()

    val pauseCallsWhenAudioFocusIsLostListener = object : Module_Phone_SettingListenerStub() {
        override fun onBoolValueChanged(newValue: Boolean) {
            prefs.pauseCallsWhenAudioFocusIsLost = newValue
        }
    }

    val pauseCallsWhenAudioFocusIsLost = MutableLiveData<Boolean>()

    val goToAndroidNotificationSettingsListener = object : Module_Phone_SettingListenerStub() {
        override fun onClicked() {
            goToAndroidNotificationSettingsEvent.value = Module_Phone_Event(true)
        }
    }
    val goToAndroidNotificationSettingsEvent = MutableLiveData<Module_Phone_Event<Boolean>>()

    // region Video Settings
    val enableVideo = MutableLiveData<Boolean>()
    val videoSizeIndex = MutableLiveData<Int>()
    val videoSizeLabels = MutableLiveData<ArrayList<String>>()

    val videoPresetListener = object : Module_Phone_SettingListenerStub() {
        override fun onListValueChanged(position: Int) {
            videoPresetIndex.value = position // Needed to display/hide two below settings
        }
    }
    val videoPresetIndex = MutableLiveData<Int>()
    val videoPresetLabels = MutableLiveData<ArrayList<String>>()

    val preferredFpsListener = object : Module_Phone_SettingListenerStub() {
        override fun onListValueChanged(position: Int) {
            preferredFpsIndex.value = position
        }
    }
    val preferredFpsIndex = MutableLiveData<Int>()
    val preferredFpsLabels = MutableLiveData<ArrayList<String>>()

    val videoSizeListener = object : Module_Phone_SettingListenerStub() {
        override fun onListValueChanged(position: Int) {
            videoSizeIndex.value = position
        }
    }

    private fun initVideoSizeList() {
        val labels = arrayListOf<String>()

        for (size in Factory.instance().supportedVideoDefinitions) {
            val videoSizeStr = size.name.orEmpty()

            labels.add(videoSizeStr.uppercase())
        }

        videoSizeLabels.value = labels
        videoSizeIndex.value = labels.indexOf(core.preferredVideoDefinition.name?.uppercase())
    }

    private fun initVideoPresetList() {
        val labels = arrayListOf<String>()

        labels.add("default")
        labels.add("high-fps")
        labels.add("custom")

        videoPresetLabels.value = labels
        videoPresetIndex.value = labels.indexOf(core.videoPreset)
        if (videoPresetIndex.value!! < 0) {
            videoPresetIndex.value = 0
        }
    }

    private fun initFpsList() {
        val labels = arrayListOf("5", "10", "15", "20", "25", "30")
        preferredFpsLabels.value = labels
        preferredFpsIndex.value = labels.indexOf(core.preferredFramerate.toInt().toString())
    }
    // endregion

    init {
        var startTime = System.currentTimeMillis()
        Log.e("jake1", " @[CallSettingsViewModel] ==>  init() ")
        initAudioParams()
        initVideoParams()
        initRingtonesList()
//        core.ringDuringIncomingEarlyMedia = true
        deviceRingtone.value = core.ring == null
        showRingtonesList.value = prefs.showAllRingtones
        vibrateOnIncomingCall.value = core.isVibrationOnIncomingCallEnabled
        //        initEncryptionList()
        encryptionMandatory.value = core.isMediaEncryptionMandatory
//        useTelecomManager.value = prefs.useTelecomManager
//        api26OrHigher.value = Version.sdkAboveOrEqual(Version.API26_O_80)
//        fullScreen.value = prefs.fullScreenCallUI
//        overlay.value = prefs.showCallOverlay
//        systemWideOverlay.value = prefs.systemWideCallOverlay
//        sipInfoDtmf.value = core.useInfoForDtmf
        //        rfc2833Dtmf.value = core.useRfc2833ForDtmf
        //        autoStartCallRecording.value = prefs.automaticallyStartCallRecording
//        autoStart.value = prefs.callRightAway
//        autoAnswer.value = core.isKeepAliveEnabled
//        autoAnswerDelay.value = core.keepaliveInterval
//        incomingTimeout.value = core.incTimeout
        //        voiceMailUri.value = prefs.voiceMailUri
        //        redirectToVoiceMailIncomingDeclinedCalls.value = prefs.redirectDeclinedCallToVoiceMail
        acceptEarlyMedia.value = prefs.globalSupportEarlyMedia
        ringDuringEarlyMedia.value = core.ringDuringIncomingEarlyMedia
//        pauseCallsWhenAudioFocusIsLost.value = prefs.pauseCallsWhenAudioFocusIsLost

        videoPayloadNum.value = core.videoPayloadTypes[0].number
        audioPayloadNum.value = core.audioPayloadTypes[0].number

        initOriginTmpValue()

        Log.e(
            "jake1",
            " @[CallSettingsViewModel] ==>  init -> Time  ${System.currentTimeMillis() - startTime}"
        )
    }

    private fun initOriginTmpValue() {
        echoCancellationTmp = echoCancellation.value!!
        codecBitrateIndexTmp = codecBitrateIndex.value!!
        videoSizeIndexTmp = videoSizeIndex.value!!
        Log.e("jake", "CallSettingsViewModel=>videoPresetIndex......${videoPresetIndex.value}")
        videoPresetIndexTmp = videoPresetIndex.value!!
        Log.e("jake", "CallSettingsViewModel=>videoPresetIndexTmp......$videoPresetIndexTmp")
        preferredFpsIndexTmp = preferredFpsIndex.value!!
        ringtoneIndexTmp = ringtoneIndex.value!!
        vibrateOnIncomingCallTmp = vibrateOnIncomingCall.value!!
        acceptEarlyMediaTmp = acceptEarlyMedia.value!!
        ringDuringEarlyMediaTmp = ringDuringEarlyMedia.value!!
        audioPayloadNumTmp = audioPayloadNum.value!!
        videoPayloadNumTmp = videoPayloadNum.value!!
    }

    private fun initVideoParams() {
        enableVideo.value = core.isVideoEnabled && core.videoSupported()
        initVideoSizeList()
        initVideoPresetList()
        initFpsList()
    }

    private fun initAudioParams() {
        echoCancellation.value = core.isEchoCancellationEnabled
        echoCalibration.value = if (core.isEchoCancellationEnabled) {
            prefs.getString(R.string.audio_settings_echo_cancellation_calibration_value)
                .format(prefs.echoCancellerCalibration)
        } else {
            prefs.getString(R.string.audio_settings_echo_canceller_calibration_summary)
        }
        echoTesterStatus.value = prefs.getString(R.string.audio_settings_echo_tester_summary)
        initCodecBitrateList()
    }

    private fun initCodecBitrateList() {
        val labels = arrayListOf<String>()
        for (value in codecBitrateValues) {
            labels.add("$value kbits/s")
        }
        codecBitrateLabels.value = labels

        var currentValue = 36
        for (payloadType in core.audioPayloadTypes) {
            if (payloadType.isVbr && payloadType.normalBitrate in codecBitrateValues) {
                currentValue = payloadType.normalBitrate
                break
            }
        }
        codecBitrateIndex.value = codecBitrateValues.indexOf(currentValue)
    }

    private fun initRingtonesList() {
        val labels = arrayListOf<String>()
        labels.add(Module_Phone_AppUtils.getString(R.string.call_settings_device_ringtone_title))
        ringtoneValues.add("")

        val directory = File(prefs.ringtonesPath)
        val files = directory.listFiles()
        for (ringtone in files.orEmpty()) {
            if (ringtone.absolutePath.endsWith(".mkv")) {
                val name = ringtone.name
                    .substringBefore(".")
                    .replace("_", " ")
                    .capitalize(Locale.getDefault())
                labels.add(name)
                ringtoneValues.add(ringtone.absolutePath)
            }
        }

        ringtoneLabels.value = labels
        ringtoneIndex.value = if (core.ring == null) 0 else ringtoneValues.indexOf(core.ring)
    }

    private fun initEncryptionList() {
        val labels = arrayListOf<String>()

        labels.add(prefs.getString(R.string.call_settings_media_encryption_none))
        encryptionValues.add(MediaEncryption.None.toInt())

        if (core.mediaEncryptionSupported(MediaEncryption.SRTP)) {
            labels.add(prefs.getString(R.string.call_settings_media_encryption_srtp))
            encryptionValues.add(MediaEncryption.SRTP.toInt())
        }
        if (core.mediaEncryptionSupported(MediaEncryption.ZRTP)) {
            labels.add(prefs.getString(R.string.call_settings_media_encryption_zrtp))
            encryptionValues.add(MediaEncryption.ZRTP.toInt())
        }
        if (core.mediaEncryptionSupported(MediaEncryption.DTLS)) {
            labels.add(prefs.getString(R.string.call_settings_media_encryption_dtls))
            encryptionValues.add(MediaEncryption.DTLS.toInt())
        }

        encryptionLabels.value = labels
        encryptionIndex.value = encryptionValues.indexOf(core.mediaEncryption.toInt())
    }

    fun savePreferenceChanged() {
        if (echoCancellationTmp != echoCancellation.value) {
            core.isEchoCancellationEnabled = echoCancellation.value!!
            echoCancellationTmp = echoCancellation.value!!
        }

        if (codecBitrateIndexTmp != codecBitrateIndex.value) {
            for (payloadType in core.audioPayloadTypes) {
                if (payloadType.isVbr) {
                    payloadType.normalBitrate = codecBitrateValues[codecBitrateIndex.value!!]
                }
            }
            codecBitrateIndexTmp = codecBitrateIndex.value!!
        }

        if (videoSizeIndexTmp != videoSizeIndex.value!!) {
            core.setPreferredVideoDefinitionByName(videoSizeLabels.value.orEmpty()[videoSizeIndex.value!!])
            videoSizeIndexTmp = videoSizeIndex.value!!
        }

        if (videoPresetIndexTmp != videoPresetIndex.value!!) {
            core.videoPreset = videoPresetLabels.value.orEmpty()[videoPresetIndex.value!!]
            videoPresetIndexTmp = videoPresetIndex.value!!
        }

        if (preferredFpsIndexTmp != preferredFpsIndex.value!!) {
            core.preferredFramerate =
                preferredFpsLabels.value.orEmpty()[preferredFpsIndex.value!!].toFloat()
            preferredFpsIndexTmp = preferredFpsIndex.value!!
        }

        if (ringtoneIndexTmp != ringtoneIndex.value!!) {
            if (ringtoneIndex.value!! == 0) {
                core.ring = null
            } else {
                core.ring = ringtoneValues[ringtoneIndex.value!!]
            }
            ringtoneIndexTmp = ringtoneIndex.value!!
        }

        if (vibrateOnIncomingCallTmp != vibrateOnIncomingCall.value!!) {
            core.isVibrationOnIncomingCallEnabled = vibrateOnIncomingCall.value!!
            vibrateOnIncomingCallTmp = vibrateOnIncomingCall.value!!
        }

        if (acceptEarlyMediaTmp != acceptEarlyMedia.value!!) {
            prefs.globalSupportEarlyMedia = acceptEarlyMedia.value!!
            core.ringDuringIncomingEarlyMedia = acceptEarlyMedia.value!!
            acceptEarlyMediaTmp = acceptEarlyMedia.value!!
        }

        if (ringDuringEarlyMediaTmp != ringDuringEarlyMedia.value!!) {
            core.ringDuringIncomingEarlyMedia = ringDuringEarlyMedia.value!!
            ringDuringEarlyMediaTmp = ringDuringEarlyMedia.value!!
        }

        if (audioPayloadNumTmp != audioPayloadNum.value!!) {
            core.audioPayloadTypes[0].number = audioPayloadNum.value!!
            audioPayloadNumTmp = audioPayloadNum.value!!
        }

        if (videoPayloadNumTmp != videoPayloadNum.value!!) {
            core.videoPayloadTypes[0].number = videoPayloadNum.value!!
            videoPayloadNumTmp = videoPayloadNum.value!!
        }
    }

    fun checkPreferenceChanged(): Boolean {
        Log.e("jake->", "$echoCancellationTmp :::: ${echoCancellation.value!!}")
        Log.e("jake->", "$codecBitrateIndexTmp :::: ${codecBitrateIndex.value!!}")
        Log.e("jake->", "$videoSizeIndexTmp :::: ${videoSizeIndex.value!!}")
        Log.e("jake->", "$videoPresetIndexTmp :::: ${videoPresetIndex.value!!}")
        Log.e("jake->", "$preferredFpsIndexTmp :::: ${preferredFpsIndex.value!!}")
        Log.e("jake->", "$ringtoneIndexTmp :::: ${ringtoneIndex.value!!}")
        Log.e("jake->", "$vibrateOnIncomingCallTmp :::: ${vibrateOnIncomingCall.value!!}")
        Log.e("jake->", "$acceptEarlyMediaTmp :::: ${acceptEarlyMedia.value!!}")
        Log.e("jake->", "$ringDuringEarlyMediaTmp :::: ${ringDuringEarlyMedia.value!!}")

        if (echoCancellationTmp != echoCancellation.value!! ||
            codecBitrateIndexTmp != codecBitrateIndex.value!! ||
            videoSizeIndexTmp != videoSizeIndex.value!! ||
            videoPresetIndexTmp != videoPresetIndex.value!! ||
            preferredFpsIndexTmp != preferredFpsIndex.value!! ||
            ringtoneIndexTmp != ringtoneIndex.value!! ||
            vibrateOnIncomingCallTmp != vibrateOnIncomingCall.value!! ||
            acceptEarlyMediaTmp != acceptEarlyMedia.value!! ||
            ringDuringEarlyMediaTmp != ringDuringEarlyMedia.value!!
        ) {
            return true
        }
        return false
    }
}
